package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadApiService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;


@Slf4j
@Service
public class FileUploadApiServiceImpl implements FileUploadApiService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    private VodService vodService;

    @Override
    public String fileUpload(MultipartFile multipartFile) {
        //1 判断文件是否为空
        try {
            if (multipartFile.isEmpty()){
                throw new GuiguException(400, "文件为空");
            }
            //2 判断文件是否为图片
            BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
            if (bufferedImage==null){
                throw new GuiguException(400, "文件不是图片");
            }
            //3 判读文件大小
            int imageWidth = bufferedImage.getWidth();
            int imageHeight = bufferedImage.getHeight();
            if (imageWidth > 900 || imageHeight > 900){
                throw new GuiguException(400, "图片大小不能大于900*900");
            }
            if(!vodService.scanImage(multipartFile)){
                throw new GuiguException(400, "图片包含违规内容");
            }
        } catch (Exception e) {
            throw new GuiguException(400, "文件格式有误");
        }
        try {
            //4 定义文件的存储路径 日期/文件名.后缀
            String formatName= DateUtil.today();
            String fileName = IdUtil.randomUUID();
            String extName = FileNameUtil.extName(multipartFile.getOriginalFilename());
            String filePath = "/" + formatName + "/" + fileName + "." + extName;
            //5 把文件保存到MinIO中
            String bucketName = minioConstantProperties.getBucketName();
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(filePath)
                            .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                            .contentType(multipartFile.getContentType())
                            .build());

            return minioConstantProperties.getEndpointUrl()+"/"+bucketName+filePath;
        } catch (Exception e) {
            throw new GuiguException(500, "文件上传失败");
        }
    }
}
